import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeRouter, removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getAsyncRoutes } from '@/utils/asyncRouter'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/index', '/detail', '/404', '/401'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // 判断用户是否登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/dashboard/dashboard' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // 异步获取store中的路由
      const hasRouters = store.getters.routerList && store.getters.routerList.length > 0
      // 判断store中是否有路由，若有，进行下一步
      if (hasRouters) {
        next()
      } else {
        // store中没有路由，则需要获取获取异步路由，并进行格式化处理
        try {
          const routerList = await store.dispatch('user/getRouterList')
          const accessRoutes = getAsyncRoutes(routerList)
          // 临时加入模板
          asyncRoutes.forEach(item => {
            accessRoutes.push(item)
          })
          // 存路由到 permission 中的 stores 侧边栏使用
          store.commit('permission/SET_ROUTES', accessRoutes)
          // 动态添加格式化过的路由
          router.addRoutes(accessRoutes)

          // 获取用户信息，存入缓存
          await store.dispatch('user/getInfo')

          // 放行
          next({ ...to, replace: true })
        } catch (error) {
          removeToken()
          removeRouter()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // 其他无权访问的页面被重定向到登录页面.
      next({ path: `/login?redirect=${to.path}`, query: to.query })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
